import 'dart:convert';

import 'package:dali_ng_pera/manager/dnp_plugin_manager.dart';
import 'package:dali_ng_pera/net/dnp_net_manager.dart';
import 'package:dali_ng_pera/page/certification/model/dnp_emergency_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;

class DnpEmergencyController extends GetxController {
  final emergencyModels = <DnpEmergencyModel>[].obs;

  void onRequestData(String already) {
    DnpPluginManager().showLoading();
    DnpNetManager()
        .post("/haseye/hou", data: dio.FormData.fromMap({"already": already}))
        .then((value) {
      DnpPluginManager().hideLoading();
      if (value.success && value.iesous == "0") {
        try {
          List result = value.close["obscure"];
          emergencyModels.value =
              result.map((e) => DnpEmergencyModel.fromJson(e)).toList();
          print("object");
        } catch (e) {
          DnpPluginManager().showToast(e.toString());
        }
      } else {
        DnpPluginManager().showToast(value.kurios ?? "");
      }
    });
  }

  void onSubmit(String already,VoidCallback callback) {
    List subList = [];
    for (var item in emergencyModels) {
      String? beersheba = item.beersheba;
      String? most = item.most;
      int? christian = int.tryParse(item.christian ?? "");
      subList
          .add({"beersheba": beersheba, "most": most, "christian": christian});
    }
    DnpPluginManager().showLoading();
    DnpNetManager()
        .post("/haseye/ex",
            data: dio.FormData.fromMap({"already": already, "close": jsonEncode(subList)}))
        .then((value) {
      DnpPluginManager().hideLoading();
      if (value.success && value.iesous == "0") {
        try {
          callback();
          Get.back();
        } catch (e) {
          DnpPluginManager().showToast(e.toString());
        }
      } else {
        DnpPluginManager().showToast(value.kurios ?? "");
      }
    });
  }

  String getBeersheba(String? christian,List<DnpUsually>? model){
    if(model == null || model.isEmpty){
      return "";
    }
    for(var item in model){
      if(item.heard == christian){
        return item.beersheba??"";
      }
    }
    return "";
  }
}
